
/*
 *  Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.client.core.view.analysis.report;

import com.google.common.collect.Lists;
import com.intelligent.ispc.client.MainFrame;
import com.intelligent.ispc.client.core.controller.YieldController;
import com.intelligent.ispc.client.core.modal.report.YieldHistoryDataModel;
import com.intelligent.ispc.client.core.modal.report.YieldMainDataModel;
import com.intelligent.ispc.client.core.validator.UslAndLslDto;
import com.intelligent.ispc.client.core.view.AbstractPanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisFilePanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisItemPanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisSearchPanel;
import com.intelligent.ispc.client.event.ExportBtnEnabledEvent;
import com.intelligent.ispc.client.utils.*;
import com.intelligent.ispc.client.utils.validation.GuiComponentFactory;
import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.core.dto.*;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.jxlayer.JXLayer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.text.JTextComponent;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by cherry on 2016/7/12.
 * Update by Lucien.Chen on 2016/8/29
 */
@org.springframework.stereotype.Component
public class YieldPanel extends AbstractPanel {
    @Autowired
    private YieldController yieldController;

    /**
     * construction
     */
    public YieldPanel() {

    }

    @Override
    public void initDataSource() {
        analysisFilePanel.initDataSource();
        analysisSearchPanel.setBaseFields(Lists.newArrayList());
    }

    @Override
    public void initView() {
        analysisFilePanel.initView();
        showTopBar();
        fireCleanPanel();
    }

    @Override
    @PostConstruct
    public void initComponents() {

        JPanel rightPanel;
        rightPanel = new JPanel();
        rightPanel.setLayout(new GridBagLayout());
        yieldPanel = new JPanel();
        historyPanel = new JPanel();
        topBarPanel = new JPanel();

        group1ComboBox = new JComboBox();
        group2ComboBox = new JComboBox();
        searchButton = new JButton("Search");
        searchButton.setEnabled(false);
        analysisFilePanel = new AnalysisFilePanel(UIConstant.MODULE_YIELD);
        analysisItemPanel = new AnalysisItemPanel(UIConstant.MODULE_YIELD);
        analysisSearchPanel = new AnalysisSearchPanel(UIConstant.MODULE_YIELD);

        //init left search
        final Dimension analysisSearchPanelSize = new Dimension(150, 150);
        analysisSearchPanel.setPreferredSize(analysisSearchPanelSize);
        JPanel groupPanel = new JPanel();
        groupPanel.setLayout(new GridBagLayout());
        final Dimension groupPanelSize = new Dimension(150, 60);
        groupPanel.setPreferredSize(groupPanelSize);
        groupPanel.add(new JLabel("group1"), new GBC(0, 1, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(0, 0).setInsets(0, 0, 5, 5));
        groupPanel.add(group1ComboBox, new GBC(1, 1, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(80, 0).setInsets(0, 0, 5, 5));
        groupPanel.add(new JLabel("group2"), new GBC(0, 3, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(0, 0).setInsets(0, 0, 5, 5));
        groupPanel.add(group2ComboBox, new GBC(1, 3, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(80, 0).setInsets(0, 0, 5, 5));

        JPanel paramPanel = new JPanel();
        paramPanel.setLayout(new GridBagLayout());
        final Dimension paramPanelSize = new Dimension(150, 30);
        paramPanel.setPreferredSize(paramPanelSize);
        bg = new BindingGroup();
        uslAndLslDto = new UslAndLslDto();
        uslText = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_USL);
        uslText.getView().setEnabled(false);
        lslText = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_LSL);
        lslText.getView().setEnabled(false);
        paramPanel.add(new JLabel("USL"), new GBC(0, 0, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(0, 0).setInsets(0, 0, 5, 5));
        paramPanel.add(uslText, new GBC(1, 0, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(100, 0).setInsets(0, 0, 5, 5));
        paramPanel.add(new JLabel("LSL"), new GBC(2, 0, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(0, 0).setInsets(0, 0, 5, 5));
        paramPanel.add(lslText, new GBC(3, 0, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTHEAST).setWeight(100, 0).setInsets(0, 0, 5, 5));

        JPanel leftPanel = new JPanel(new GridBagLayout());
        leftPanel.add(analysisFilePanel, new GBC(0, 0, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(analysisItemPanel, new GBC(0, 1, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(analysisSearchPanel, new GBC(0, 2, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(groupPanel, new GBC(0, 3, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(0, 0));
        leftPanel.add(paramPanel, new GBC(0, 4, 1, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(0, 0));
        leftPanel.add(searchButton, new GBC(0, 5, 1, 1).setFill(GBC.HORIZONTAL).setAnchor(GBC.NORTH).setWeight(100, 100));
        JScrollPane leftScroll = new JScrollPane();
        leftScroll.setViewportView(leftPanel);
        leftScroll.setBorder(BorderFactory.createEmptyBorder());
        leftScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        final Dimension leftScrollSize = new Dimension(200, 100);
        leftScroll.setPreferredSize(leftScrollSize);

        JScrollPane rightScrollPanel = new JScrollPane();
        rightScrollPanel.setViewportView(rightPanel);
        rightScrollPanel.setBorder(BorderFactory.createEmptyBorder());

        rightPanel.setBorder(BorderFactory.createEmptyBorder());
        rightPanel.add(topBarPanel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setAnchor(GBC.NORTHEAST).setWeight(100, 0));
        rightPanel.add(yieldPanel, new GBC(0, 1).setFill(GBC.HORIZONTAL).setAnchor(GBC.NORTHWEST).setWeight(100, 0));
        rightPanel.add(historyPanel, new GBC(0, 2).setFill(GBC.HORIZONTAL).setAnchor(GBC.NORTHWEST).setWeight(100, 100));

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, leftScroll, rightScrollPanel);
        splitPane.setDividerSize(5);

        this.setLayout(new GridBagLayout());
        this.add(splitPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        initComponentEvent();
    }

    /**
     * @return searchButton is whether enabled or not?
     */
    public boolean getSearchBtnStatus() {
        return searchButton.isEnabled();
    }

    /**
     * when file param is changed, clear or init left panel
     *
     * @param files current choose file
     */
    public void onFileChange(List<String> files) {
        if (files == null || files.isEmpty()) {
            fireCleanPanel();
        } else {
            fireCleanPanel();
            yieldController.findSearchKey(files);
        }
    }

    /**
     * choose file is changed
     *
     * @param isMatched current file compare with cache
     */
    public void onChooseFileChange(boolean isMatched) {
        fileFlag = isMatched;
        setBtnEnable();
    }

    /**
     * choose item is changed
     *
     * @param isMatched current item compare with cache
     */
    public void onChooseItemChange(boolean isMatched) {
        testItemFlag = isMatched;
        setBtnEnable();
    }

    /**
     * search condition is changed
     *
     * @param isMatched current condition compare with cache
     */
    public void onSearchConditionChange(boolean isMatched) {
        searchKeyFlag = isMatched;
        setBtnEnable();
    }

    /**
     * clean all components and flags
     */
    public void fireCleanPanel() {
        if (yieldPanel != null) {
            yieldPanel.removeAll();
        } else {
            yieldPanel = new JPanel();
        }
        clearHistory();

        analysisItemPanel.onReceivedTestItems(new ArrayList<>());
        analysisSearchPanel.setBaseFields(new ArrayList<>());
        groupKeys = null;
        group1ComboBox.setSelectedItem("");
        group1ComboBox.removeAllItems();
        group2ComboBox.setSelectedItem("");
        group2ComboBox.removeAllItems();
        uslAndLslDto.setUslValue(null);
        uslText.getView().setEnabled(false);
        uslAndLslDto.setLslValue(null);
        uslText.getView().setEnabled(false);
        fileFlag = false;
        analyseFlag = false;
        searchKeyFlag = false;
        searchFlag = false;
        groupsFlag = false;
        setBtnEnable();
        ApplicationBeanUtils.getBean(MainFrame.class).revalidate();
    }

    /**
     * init group component
     */
    public void initGroup() {
        group1ComboBox.setSelectedItem("");
        group1ComboBox.removeAllItems();
        group2ComboBox.setSelectedItem("");
        group2ComboBox.removeAllItems();
        group1ComboBox.addItem("");
        for (int i = 0; i < groupKeys.size(); i++) {
            group1ComboBox.addItem(groupKeys.get(i));
        }
        group2ComboBox.addItem("");
        for (int i = 0; i < groupKeys.size(); i++) {
            group2ComboBox.addItem(groupKeys.get(i));
        }
        fileFlag = true;
        analyseFlag = true;
        searchButton.setEnabled(true);
    }

    public AnalysisItemPanel getAnalysisItemPanel() {
        return analysisItemPanel;
    }

    public AnalysisSearchPanel getAnalysisSearchPanel() {
        return analysisSearchPanel;
    }

    /**
     * seach finish for success
     */
    public void fireSearchActionPerformed() {
        clearHistory();
        showYiledTable();
    }

    /**
     * show usl and lsl after selected a item
     */
    public void fireSelectOneItem() {
        uslAndLslDtoSource = yieldController.findYieldItemParam(getFilePath(), getTestItemName());
        uslAndLslDto.setUslValue(uslAndLslDtoSource.getUslValue());
        uslText.getView().setEnabled(true);
        uslAndLslDto.setLslValue(uslAndLslDtoSource.getLslValue());
        lslText.getView().setEnabled(true);
    }

    /**
     * set yield data to model
     *
     * @param yieldDtos yield data
     */
    public void setYieldData(List<YieldDto> yieldDtos) {
        String[] columns = {
                "Group", "First Inspect", "First Pass", "First Fail", "FPY", "ReTest Inspect", "ReTest Pass", "ReTest Fail", "ReTest Yield", "Total Yield"
        };
        yieldModel = new YieldMainDataModel(columns);
        if (yieldDtos != null) {
            yieldModel.setData(yieldDtos);
            yieldTable.setModel(yieldModel);

            analysisSearchPanel.setCacheData(analysisSearchPanel.getSearchParams());
            testItemFlag = true;
            searchKeyFlag = true;
            searchFlag = true;
            groupCaches = getGroupKeys();
            groupsFlag = true;
            uslAndLslCaches = new UslAndLslDto();
            uslAndLslCaches.setUslValue(uslAndLslDto.getUslValue());
            uslAndLslCaches.setLslValue(uslAndLslDto.getLslValue());
            setBtnEnable();
        }
    }

    /**
     * set history data to model
     *
     * @param yieldHistoryDto history data
     */
    public void setHistoryData(YieldHistoryDto yieldHistoryDto) {
        if (yieldHistoryDto != null) {
            historyModel = new YieldHistoryDataModel(yieldHistoryDto.getColumnNames());
            historyModel.setData(yieldHistoryDto.getColumnValues());
            historyTable.setModel(historyModel);
        }
    }

    public void setGroupKeys(List<String> groupKeys) {
        this.groupKeys = groupKeys;
    }

    /**
     * @param invoker button
     */
    public void showExportMenu(Component invoker) {
        final int hight = 25;
        exportMnu.show(invoker, 0, hight);
    }

    /*
     *add listeners
     */
    private void initComponentEvent() {

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateUslAndLsl()) {
                    fireSearchActionPerformed();
                    analysisItemPanel.setCacheData(analysisItemPanel.getSelectedName());
                }
            }
        });

        group1ComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    mutexForGroup();
                    groupsFlag = isValidGroups();
                    setBtnEnable();
                }
            }
        });

        group2ComboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    mutexForGroup();
                    groupsFlag = isValidGroups();
                    setBtnEnable();
                }
            }
        });

    }

    /*
     *campare groups between current`s and caches
     */
    private boolean isValidGroups() {
        if (groupCaches == null) {
            return true;
        }
        List<String> currentGroups = getGroupKeys();
        if (groupCaches.size() != currentGroups.size()) {
            return false;
        }

        if (!groupCaches.equals(currentGroups)) {
            return false;
        }
        return true;
    }

    /*
     *campare usl and lsl between current`s and caches
     */
    private boolean isValidUslAndLsl() {
        if (uslAndLslCaches == null) {
            return true;
        }

        if (StringUtils.isBlank(uslAndLslCaches.getUslValue())) {
            if (!StringUtils.isBlank(uslAndLslDto.getUslValue())) {
                return false;
            }
        } else {
            if (!uslAndLslCaches.getUslValue().equals(uslAndLslDto.getUslValue())) {
                return false;
            }
        }

        if (StringUtils.isBlank(uslAndLslCaches.getLslValue())) {
            if (!StringUtils.isBlank(uslAndLslDto.getLslValue())) {
                return false;
            }
        } else {
            if (!uslAndLslCaches.getLslValue().equals(uslAndLslDto.getLslValue())) {
                return false;
            }
        }
        return true;
    }

    /*
     *click yield table to show history
     */
    private void clickTable(MouseEvent e) {
        Point p = e.getPoint();
        int column = yieldTable.columnAtPoint(p);
        String groupValue = yieldModel.getData().get(yieldTable.getSelectedRow()).getGroupKey();

        if (!fileFlag || !searchKeyFlag || !groupsFlag || !testItemFlag || !isValidUslAndLsl()) {
            AppMessageFactory.showWarningDialog("Search Params is changed already!");
            return;
        }

        int origin = 0;
        if (column == origin || column == origin + 4 || column == origin + 8 || column == origin + 9) {
            return;
        }

        Integer type;
        if (column == origin + 1 || column == origin + 2 || column == origin + 3) {
            type = column - origin - 1;
        } else {
            type = column - origin - 2;
        }
        showHistoryTable(groupValue, type);
    }

    /*
     *groups are unique
     */
    private void mutexForGroup() {
        addItemToComboBox(group1ComboBox, groupKeys);
        addItemToComboBox(group2ComboBox, groupKeys);
        removeItemFromComboBox(group2ComboBox.getSelectedItem(), group1ComboBox);
        removeItemFromComboBox(group1ComboBox.getSelectedItem(), group2ComboBox);
    }

    private void removeItemFromComboBox(Object item, JComboBox comboBox) {
        if (groupKeys == null || groupKeys.isEmpty()) {
            return;
        }
        ComboBoxModel groupModel = comboBox.getModel();
        int size = groupModel.getSize();
        for (int i = 1; i < size; i++) {
            if (groupModel.getElementAt(i).equals(item)) {
                comboBox.removeItemAt(i);
                break;
            }
        }
    }

    /*
     * add item form groupKeys to groups
     */
    private void addItemToComboBox(JComboBox groupComboBox, List<String> groupKeys) {
        if (groupKeys == null || groupKeys.isEmpty()) {
            return;
        }
        ComboBoxModel groupModel = groupComboBox.getModel();
        int size = groupModel.getSize();
        if (size < 2) {
            return;
        }
        for (int i = 0; i < groupKeys.size(); i++) {
            String groupKey = groupKeys.get(i);
            boolean existFlag = false;
            for (int j = 1; j < size; j++) {
                if (groupModel.getElementAt(j).equals(groupKey)) {
                    existFlag = true;
                    break;
                }
            }
            if (!existFlag) {
                groupComboBox.addItem(groupKey);
                return;
            }
        }
    }

    /*
     *return curren file path
     */
    private List<String> getFilePath() {
        List<KeyValueDto> fileDataDtos = analysisFilePanel.getSelectedFiles();
        List<String> filePath = Lists.newArrayList();
        for (int i = 0; i < fileDataDtos.size(); i++) {
            filePath.add((String) fileDataDtos.get(i).getValue());
        }
        return filePath;
    }

    /*
     *control btn
     */
    private void setBtnEnable() {
        if (searchButton != null) {
            if (fileFlag && analyseFlag) {
                searchButton.setEnabled(true);
            } else {
                searchButton.setEnabled(false);
            }
        }
        if (fileFlag && searchFlag && testItemFlag && searchKeyFlag && groupsFlag) {
            EventBusUtils.post(new ExportBtnEnabledEvent(UIConstant.MODULE_YIELD, true));
        } else {
            EventBusUtils.post(new ExportBtnEnabledEvent(UIConstant.MODULE_YIELD, false));
        }
    }

    /*
     *return current groups
     */
    private List<String> getGroupKeys() {
        List<String> groupValues = Lists.newArrayList();
        if (StringUtils.isNotBlank((String) group1ComboBox.getSelectedItem())) {
            groupValues.add((String) group1ComboBox.getSelectedItem());
        }
        if (StringUtils.isNotBlank((String) group2ComboBox.getSelectedItem())) {
            groupValues.add((String) group2ComboBox.getSelectedItem());
        }
        return groupValues;
    }

    /*
     *init exportMnu
     */
    private void showTopBar() {
        if (topBarPanel != null) {
            topBarPanel.removeAll();
        } else {
            topBarPanel = new JPanel();
        }

        topBarPanel.setLayout(new GridBagLayout());

        JLabel titleLabel = new JLabel("Analysis/Yield");
        titleLabel.setFont(FontFactory.createPageTileFont());


        exportMnu = new JPopupMenu();
        exportMnu.setBorderPainted(true);
        exportMnu.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

        JMenuItem allMnu = new JMenuItem("Summary and Detail");
        JMenuItem yieldMnu = new JMenuItem("Only Summary");
        exportMnu.add(yieldMnu);
        exportMnu.addSeparator();
        exportMnu.add(allMnu);

        final Dimension exportMnuSize = new Dimension(180, 50);
        exportMnu.setPreferredSize(exportMnuSize);

        allMnu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (searchKeyFlag) {
                    List<DynSearchFieldDto> dynSesrchFieldDto = analysisSearchPanel.getSearchParams();
                    yieldController.exportSummaryAndDetail(getFilePath(), dynSesrchFieldDto, getGroupKeys(), getTestItemName(), uslAndLslDtoSource);
                } else {
                    AppMessageFactory.showWarningDialog("Please analyse first!");
                }
            }
        });

        yieldMnu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (searchKeyFlag) {
                    List<DynSearchFieldDto> dynSesrchFieldDto = analysisSearchPanel.getSearchParams();
                    yieldController.exportSummary(getFilePath(), dynSesrchFieldDto, getGroupKeys(), getTestItemName(), uslAndLslDtoSource);
                } else {
                    AppMessageFactory.showWarningDialog("Please analyse first!");
                }
            }
        });

        topBarPanel.add(titleLabel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 5, 0, 0));
    }

    /*
     *return current item
     */
    private List<String> getTestItemName() {

        String selectItemName = analysisItemPanel.getSelectedName();
        if (selectItemName != null) {
            List<String> testItemNames = Lists.newArrayList();
            testItemNames.add(analysisItemPanel.getSelectedName());
            return testItemNames;
        } else {
            return null;
        }
    }

    /*
     *lsl < usl
     */
    private boolean validateUslAndLsl() {

        if (StringUtils.isNumeric(uslAndLslDto.getUslValue()) && StringUtils.isNumeric(uslAndLslDto.getLslValue())) {
            if (uslAndLslDto.getUslValue().equals(uslAndLslDtoSource.getUslValue())
                    && uslAndLslDto.getLslValue().equals(uslAndLslDtoSource.getLslValue())) {
                return true;
            }

            if (Double.valueOf(uslAndLslDto.getUslValue()) <= Double.valueOf(uslAndLslDto.getLslValue())) {
                AppMessageFactory.showWarningDialog("The LSL's value must less than the USL");
                return false;
            }
        }

        return true;
    }

    /*
     *init Yield table
     */
    private void showYiledTable() {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<UslAndLslDto>> validationMessages = validator.validate(uslAndLslDto);
        if (validationMessages.size() > 0) {
            AppMessageFactory.showWarningDialog("USL and LSL are not right");
            return;
        }
        if (yieldPanel != null) {
            yieldPanel.removeAll();
        } else {
            yieldPanel = new JPanel();
        }

        JScrollPane jScrollPane = new JScrollPane();
        final Dimension yieldPanelSize = new Dimension(800, 200);
        jScrollPane.setPreferredSize(yieldPanelSize);
        yieldPanel.setLayout(new GridBagLayout());
        yieldPanel.setBorder(BorderFactory.createTitledBorder("Summary"));

        yieldTable = new JTable();

        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
        tcr.setHorizontalAlignment(SwingConstants.CENTER);
        yieldTable.setDefaultRenderer(Object.class, tcr);

        jScrollPane.setViewportView(yieldTable);
//        yieldTable.setCellSelectionEnabled(true);

        yieldTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                clickTable(e);
            }
        });
        yieldPanel.add(jScrollPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        List<DynSearchFieldDto> dynSesrchFieldDto = analysisSearchPanel.getSearchParams();
        yieldController.findYield(getFilePath(), dynSesrchFieldDto, getGroupKeys(), getTestItemName(), uslAndLslDto);

        ApplicationBeanUtils.getBean(MainFrame.class).revalidate();
    }

    /*
     * init history table
     */
    private void showHistoryTable(String groupValue, Integer type) {
        clearHistory();
        historyPanel.setLayout(new GridBagLayout());
        String title = "Detail";
        title = title + (getColumName(type) != null ? "-" + getColumName(type) : "");
        historyPanel.setBorder(BorderFactory.createTitledBorder(title));

        JScrollPane jScrollPane = new JScrollPane();
        final Dimension historyPanelSize = new Dimension(800, 200);
        jScrollPane.setPreferredSize(historyPanelSize);
        historyTable = new JTable();
        jScrollPane.setViewportView(historyTable);
        historyPanel.add(jScrollPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));

        List<DynSearchFieldDto> dynSesrchFieldDto = analysisSearchPanel.getSearchParams();
        yieldController.findHistory(getFilePath(), dynSesrchFieldDto, getGroupKeys(), groupValue, type, getTestItemName(), uslAndLslDto);

        ApplicationBeanUtils.getBean(MainFrame.class).revalidate();
    }

    private void clearHistory() {
        if (historyPanel != null) {
            historyPanel.removeAll();
        } else {
            historyPanel = new JPanel();
        }
    }

    /*
     *use type to find colum name
     */
    private String getColumName(Integer type) {
        switch (type) {
            case 0:
                return "First Inspect";
            case 1:
                return "First Pass";
            case 2:
                return "First Fail";
            case 3:
                return "ReTest Inspect";
            case 4:
                return "ReTest Pass";
            case 5:
                return "ReTest Fail";
            default:
                return null;
        }
    }

    private AnalysisFilePanel analysisFilePanel;
    private AnalysisItemPanel analysisItemPanel;
    private AnalysisSearchPanel analysisSearchPanel;

    private List<String> groupCaches;
    private UslAndLslDto uslAndLslCaches;
    private boolean fileFlag = false;
    private boolean analyseFlag = false;
    private boolean testItemFlag = false;
    private boolean searchKeyFlag = false;
    private boolean searchFlag = false;
    private boolean groupsFlag = false;

    private JTable yieldTable;
    private JTable historyTable;
    private YieldMainDataModel yieldModel;
    private YieldHistoryDataModel historyModel;
    private List<String> groupKeys;
    private JComboBox group1ComboBox;
    private JComboBox group2ComboBox;
    private JButton searchButton;
    //    private JButton exportBtn;
    private JPopupMenu exportMnu;
    private BindingGroup bg;
    private UslAndLslDto uslAndLslDto;
    private UslAndLslDto uslAndLslDtoSource;

    private JXLayer<JTextComponent> uslText;
    private JXLayer<JTextComponent> lslText;
    private JPanel topBarPanel;
    private JPanel yieldPanel;
    private JPanel historyPanel;

}

